package com.atguigu.atcrowdfunding.potal.controller;

import com.atguigu.atcrowdfunding.bean.Cert;
import com.atguigu.atcrowdfunding.bean.Member;
import com.atguigu.atcrowdfunding.bean.MemberCert;
import com.atguigu.atcrowdfunding.bean.Ticket;
import com.atguigu.atcrowdfunding.manager.service.CertService;
import com.atguigu.atcrowdfunding.potal.listener.PassListener;
import com.atguigu.atcrowdfunding.potal.listener.RefuseListener;
import com.atguigu.atcrowdfunding.potal.service.MemberService;
import com.atguigu.atcrowdfunding.potal.service.TicketService;
import com.atguigu.atcrowdfunding.util.AjaxResult;
import com.atguigu.atcrowdfunding.util.Const;
import com.atguigu.atcrowdfunding.vo.Data;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @author xzt
 * @create 2021-03-13 15:09
 */
@Controller
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private CertService certService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @RequestMapping("/accttype")
    public String accttype() {
        return "member/accttype";
    }

    @RequestMapping("/basicinfo")
    public String basicinfo() {
        return "member/apply";
    }


    @RequestMapping("/judge")
    public String judge(HttpSession session) {
        Member member = (Member) session.getAttribute(Const.LOGIN_MEMBER);

        Ticket ticket = ticketService.getTicketByMemberId(member.getId());

        if (ticket == null) {
            ticket = new Ticket();
            ticket.setMemberid(member.getId());
            ticket.setPstep("apply");
            ticket.setStatus("0");
            ticketService.saveTicket(ticket);
        } else {
            String pstep = ticket.getPstep();

            if ("accttype".equals(pstep)) {
                return "redirect:/member/basicinfo.htm";
            } else if ("basicinfo".equals(pstep)) {
                return "redirect:/member/uploadCert.htm";
            } else if ("uploadcert".equals(pstep)) {
                return "redirect:/member/checkemail.htm";
            } else if ("checkemail".equals(pstep)) {
                return "redirect:/member/checkauthcode.htm";
            }

        }

        return "/member/accttype";
    }

    @RequestMapping("/checkauthcode")
    public String checkauthcode() {
        return "/member/checkauthcode";
    }

    @ResponseBody
    @RequestMapping("/updateBasicinfo")
    public Object updateBasicinfo(HttpSession session, Member member) {
        AjaxResult ajaxResult = new AjaxResult();
        try {

            Member loginMember = (Member) session.getAttribute(Const.LOGIN_MEMBER);

            loginMember.setRealname(member.getRealname());
            loginMember.setCardnum(member.getCardnum());
            loginMember.setTel(member.getTel());

            memberService.updateBasicinfo(loginMember);

            Ticket ticket = ticketService.getTicketByMemberId(loginMember.getId());
            ticket.setPstep("basicinfo");
            ticketService.updatePstep(ticket);

            ajaxResult.setSuccess(true);
            ajaxResult.setMessage("个人信息提交成功");

        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("个人信息提交失败");
            e.printStackTrace();
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/updateAcctType")
    public Object updateAcctType(HttpSession session, String accttype) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            Member member = (Member) session.getAttribute(Const.LOGIN_MEMBER);
            member.setAccttype(accttype);
            //更新账户类型
            memberService.updateAcctType(member);

            //更新流程单
            Ticket ticket = ticketService.getTicketByMemberId(member.getId());
            ticket.setPstep("accttype");
            ticketService.updatePstep(ticket);


            ajaxResult.setSuccess(true);
            ajaxResult.setMessage("账户类型更新成功");

        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("账户类型更新失败");
            e.printStackTrace();
        }
        return ajaxResult;
    }

    @RequestMapping("/uploadCert")
    public String uploadCert(HttpSession session, Model model) {
        Member member = (Member) session.getAttribute(Const.LOGIN_MEMBER);
        String accttype = member.getAccttype();
        List<Cert> certs = certService.queryCertByAccttype(accttype);

        model.addAttribute("certs", certs);
        return "member/uploadCert";
    }

    @ResponseBody
    @RequestMapping("/doUploadCert")
    public Object doUploadCert(HttpSession session, Data data) {

        AjaxResult ajaxResult = new AjaxResult();

        try {
            //获取会员信息
            Member loginMember = (Member) session.getAttribute(Const.LOGIN_MEMBER);

            //保存会员与资质关系数据
            List<MemberCert> certimgs = data.getCertimgs();
            ServletContext servletContext = session.getServletContext();
            String realPath = servletContext.getRealPath("/pics");
            for (MemberCert certimg : certimgs) {
                //资质文件上传
                MultipartFile fileImg = certimg.getFileImg();
                String extName = fileImg.getOriginalFilename().substring(fileImg.getOriginalFilename().lastIndexOf("."));
                String tempName = UUID.randomUUID().toString() + extName;
                String filename = realPath + "/cert" + "/" + tempName;
                fileImg.transferTo(new File(filename));

                //封住数据，保存数据库
                certimg.setIconpath(tempName);
                certimg.setMemberid(loginMember.getId());
            }

            certService.saveMemberCert(certimgs);

            //记录流程步骤
            Ticket ticket = ticketService.getTicketByMemberId(loginMember.getId());
            ticket.setPstep("uploadcert");
            ticketService.updatePstep(ticket);

            ajaxResult.setSuccess(true);
            ajaxResult.setMessage("上传资质文件成功");
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("上传资质文件失败");
            e.printStackTrace();
        }
        return ajaxResult;
    }

    @RequestMapping("/checkemail")
    public String checkemail() {
        return "member/checkemail";
    }

    @ResponseBody
    @RequestMapping("/startProcess")
    public Object startProcess(HttpSession session, String email) {

        AjaxResult ajaxResult = new AjaxResult();

        try {
            //获取会员信息
            Member loginMember = (Member) session.getAttribute(Const.LOGIN_MEMBER);

            //如果用户输入了新的邮箱，将旧的邮箱地址替换

            if (!loginMember.getEmail().equals(email)) {
                loginMember.setEmail(email);
                memberService.updateEmail(loginMember);
            }

            //启动实名认证的流程 - 系统自动发送邮件，生成验证码。验证邮箱地址是否合法
            ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
            ProcessDefinition processDefinition = processDefinitionQuery.processDefinitionKey("auth").singleResult();

            HashMap<String, Object> map = new HashMap<>();

            StringBuilder authcode = new StringBuilder();

            for (int i = 1; i <= 4; i++) {
                authcode.append(new Random().nextInt(10));
            }

            map.put("toEmail", email);
            map.put("authcode", authcode);
            map.put("loginacct", loginMember.getLoginacct());
            map.put("passListener", new PassListener());
            map.put("refuseListener", new RefuseListener());

            ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(), map);

            //记录流程步骤
            Ticket ticket = ticketService.getTicketByMemberId(loginMember.getId());
            ticket.setPstep("checkemail");
            ticket.setPiid(processInstance.getId());
            ticket.setAuthcode(authcode.toString());
            ticketService.updatePiidAndPstep(ticket);

            ajaxResult.setSuccess(true);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return ajaxResult;
    }


    @ResponseBody
    @RequestMapping("/finishApply")
    public Object finishApply(HttpSession session, String authcode) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            //获取会员信息
            Member loginMember = (Member) session.getAttribute(Const.LOGIN_MEMBER);


            //让当前系统用户完成：验证码审核任务
            Ticket ticket = ticketService.getTicketByMemberId(loginMember.getId());
            if(ticket.getAuthcode().equals(authcode)){
                //完成审核验证码任务
                Task task = taskService.createTaskQuery().processInstanceId(ticket.getPiid()).taskAssignee(loginMember.getLoginacct()).singleResult();
                taskService.complete(task.getId());

                //更新用户申请状态
                loginMember.setAuthstatus("1");
                memberService.updateAuthstatus(loginMember);

                //记录流程步骤
                ticket.setPstep("finishapply");
                ticketService.updatePstep(ticket);
                ajaxResult.setSuccess(true);
            }else{
                ajaxResult.setSuccess(false);
                ajaxResult.setMessage("验证码不正确，请重新输入！");
            }


        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            e.printStackTrace();
        }
        return ajaxResult;
    }
}
